<template>
  <div class="container">
    <BasicForm @register="handleRegisterForm">
      <template #content="{}">
        <div>
          <Dropdown
            placement="bottom"
            :trigger="['click']"
            :dropMenuList="placeholderDownList"
            @menu-event="handleMenuEvent"
            overlayClassName="app-locale-picker-overlay"
          >
            <span class="cursor-pointer flex items-center">
              <span>插入字段</span>
              <DownOutlined />
            </span>
          </Dropdown>
        </div>
        <!-- <a-textarea
          v-model:value="model[field]"
          :rows="4"
          placeholder="【短信签名】请输入短信内容"
        /> -->
        <KeywordTemplate ref="textareaRef" />
        <div
          >70字为1条短信，超出70字将会被拆分成多条发送，由于存在可插入字段，该字数统计可能不准确</div
        >
      </template>
    </BasicForm>
    <div>
      <a-button @click="handleCancel">取消</a-button>
      <a-button
        v-if="!id"
        type="primary"
        @click="handleSubmit(false)"
        :loading="saveLoading"
        class="ml-5"
        >保存</a-button
      >
      <a-button
        type="primary"
        @click="handleSubmit(true)"
        :loading="saveAndAuditLoading"
        class="ml-5"
        >{{
          (id &&
            ((detailData?.auditStatus === SmsAuditStatusEnum.PASSED && '重新提交审核') ||
              '提交审核')) ||
          '保存并提交审核'
        }}</a-button
      >
    </div>
    <MiniprogramMoadl @register="register" @ok="setSmsRouteUrl" />
  </div>
</template>

<script lang="ts" setup>
  import { BasicForm, useForm } from '@/components/Form';
  import KeywordTemplate from './KeywordTemplate/index.vue';
  import { ref } from 'vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import {
    TypeTreeDownList,
    PlaceholderDownList,
    SmsAdd,
    SmsEdit,
    SmsDetail,
    TypeById,
  } from '@/api/message/template';
  import { DropMenu, Dropdown } from '@/components/Dropdown';
  import MiniprogramMoadl from './miniprogramMoadl.vue';
  import { DownOutlined } from '@ant-design/icons-vue';
  import { useModal } from '@/components/Modal';
  import { ISmsAddData, ISmsDetailResult } from '@/api/message/template/type';
  import { useRoute } from 'vue-router';
  import { router } from '@/router';
  import { SmsAuditStatusEnum } from '@/enums/message';

  const { createMessage } = useMessage();
  const saveLoading = ref(false);
  const saveAndAuditLoading = ref(false);
  const id = ref();
  const textareaRef = ref();
  const templateTypeId = ref();

  interface formData {
    userVersion: string;
    userDesc: string;
    templateId: number;
    tenantIds: number[];
  }

  const form = ref<formData>({
    userVersion: '',
    userDesc: '',
    templateId: 0,
    tenantIds: [],
  });

  const [registerForm, { validate, setFieldsValue, submit, updateSchema }] = useForm({
    schemas: [
      {
        field: 'id',
        component: 'Input',
        label: '短信模板id',
        show: false,
      },
      {
        field: 'name',
        component: 'Input',
        label: '短信模板名称',
        required: true,
        componentProps: {
          showCount: true,
          maxlength: 12,
        },
      },
      {
        field: 'smsType',
        component: 'RadioGroup',
        label: '短信类型',
        required: true,
        componentProps: {
          options: [
            { label: '通知短信', value: 1 },
            { label: '营销短信', value: 2 },
          ],
        },
      },
      {
        field: 'smsTemplateTypeId',
        component: 'Cascader',
        label: '消息模板类型',
        required: true,
      },
      {
        field: 'smsZhContent',
        component: 'Input',
        label: '短信消息内容',
        slot: 'content',
        rules: [
          {
            required: true,
            message: '短信消息内容不能为空，且不能超过两百字',
            trigger: 'change',
          },
        ],
      },
      {
        field: 'smsRouteUrl',
        component: 'Input',
        label: '小程序链接',
        show: false,
      },
    ],
    autoFocusFirstItem: true,
    actionColOptions: {
      span: 24,
    },
    labelWidth: 120,
    baseColProps: { span: 18 },
    showSubmitButton: false,
    showResetButton: false,
    // submitButtonOptions: {
    //   text: '确认',
    // },
    // resetButtonOptions: {
    //   text: '取消',
    // },
    // submitFunc: async () => {
    //   const data: ISmsAddData = await validate();
    //   setProps({
    //     submitButtonOptions: {
    //       loading: true,
    //     },
    //   });
    //   console.log(data, form.value);
    //   try {
    //     (data.id && (await SmsEdit({ ...data }))) || (await SmsAdd({ ...data }));
    //     setProps({
    //       submitButtonOptions: {
    //         loading: false,
    //       },
    //     });

    //     createMessage.success('提交成功！');
    //     // emit('reload');
    //   } catch (error) {
    //     console.log('error--->', error);
    //     setProps({
    //       submitButtonOptions: {
    //         loading: false,
    //       },
    //     });
    //   }
    // },
    resetFunc: async () => {},
  });

  const placeholderDownList = ref<DropMenu[]>();

  async function getPlaceholderDownList(templateType: number) {
    let res = await PlaceholderDownList(templateType);
    placeholderDownList.value = res.map((item) => {
      return {
        text: item.name,
        event: item.zhPlaceholder,
      };
    });
  }

  const [register, { openModal }] = useModal();

  function handleMenuEvent(event: DropMenu) {
    let val = event.event;
    if (val === '{链接}')
      openModal(true, {
        id: templateTypeId.value,
      });
    else textareaRef.value.addKeyword(val);
  }

  function setSmsRouteUrl(smsRouteUrl: string) {
    setFieldsValue({
      smsRouteUrl,
    });
    textareaRef.value.handleBackfill('{链接}');
  }

  const route = useRoute();
  id.value = route.query.id;
  if (id.value) {
    getSmsDetail();
  }

  const detailData = ref<ISmsDetailResult>();
  async function getSmsDetail() {
    let res = await SmsDetail(id.value);
    detailData.value = res;
    setFieldsValue({
      id: res.id,
      name: res.name,
      smsType: res.smsType,
      smsTemplateTypeId: res.smsTemplateTypeId,
      smsContent: res.smsContent,
      smsRouteUrl: res.smsRouteUrl,
    });
    templateTypeId.value = res.smsTemplateTypeId;
    getPlaceholderDownList(res.smsTemplateTypeId);
    getTypeById(res.smsTemplateTypeId);
    textareaRef.value.handleBackfill(res.smsZhContent);
  }

  //根据模板类型获取详情
  async function getTypeById(id: number) {
    let res = await TypeById(id);
    setFieldsValue({
      smsTemplateTypeId: res.parentId ? [res.parentId, res.id] : [res.id],
    });
  }

  function handleCancel() {
    router.back();
  }

  async function handleRegisterForm(r: any) {
    registerForm && registerForm(r);
    let list = await TypeTreeDownList();
    updateSchema({
      field: 'smsTemplateTypeId',
      componentProps: {
        options: list,
        fieldNames: {
          label: 'name',
          value: 'id',
          children: 'nodeList',
        },
        onChange: (val) => {
          templateTypeId.value = val[val.length - 1];
          getPlaceholderDownList(templateTypeId.value);
        },
      },
    });
  }

  function handleSubmit(sudit: boolean) {
    let val = textareaRef.value.getVal();
    setFieldsValue({
      smsZhContent: val && val.length < 200 ? val : '',
    });

    submit().then(async () => {
      const data: ISmsAddData = await validate();
      if (sudit) saveAndAuditLoading.value = true;
      else saveLoading.value = true;
      console.log(data, form.value);
      try {
        const smsTemplateTypeId =
          data.smsTemplateTypeId[(data.smsTemplateTypeId as number[])?.length - 1];
        (data.id &&
          (await SmsEdit({
            ...data,
            smsZhContent: val,
            smsTemplateTypeId,
            sudit,
          }))) ||
          (await SmsAdd({ ...data, sudit, smsZhContent: val, smsTemplateTypeId }));
        if (sudit) saveAndAuditLoading.value = false;
        else saveLoading.value = false;

        createMessage.success('提交成功！');
        handleCancel();
      } catch (error) {
        console.log('error--->', error);
        if (sudit) saveAndAuditLoading.value = false;
        else saveLoading.value = false;
      }
    });
  }
</script>

<style lang="less" scoped>
  .container {
    margin: 15px;
    padding: 15px;
    background-color: #fff;
  }
</style>
